"""
文献综述生成模块
负责根据项目信息和配置生成学术文献综述
"""

import sqlite3
import uuid
from datetime import datetime
from typing import Dict, Any, Optional


def generate_literature_review(project_id: str, config: Dict[str, Any]) -> Dict[str, Any]:
    """
    生成文献综述

    Args:
        project_id: 项目ID
        config: 配置参数，包括:
            - review_type: 综述类型 (comprehensive, focused, systematic)
            - max_papers: 最大文献数量
            - keywords: 关键词列表
            - year_range: 年份范围

    Returns:
        Dict[str, Any]: 包含综述状态、内容和相关信息的字典
    """
    try:
        # 验证输入
        if not project_id or not config:
            return {
                'status': 'error',
                'message': '项目ID和配置不能为空'
            }

        # 提取配置参数
        review_type = config.get('review_type', 'comprehensive')
        max_papers = config.get('max_papers', 10)
        keywords = config.get('keywords', [])
        year_range = config.get('year_range', [2010, datetime.now().year])

        # 连接数据库
        conn = sqlite3.connect('data/research.db')
        cursor = conn.cursor()

        # 查询项目信息
        project = cursor.execute(
            'SELECT * FROM projects WHERE id = ?', (project_id,)
        ).fetchone()

        if not project:
            conn.close()
            return {
                'status': 'error',
                'message': f'未找到ID为{project_id}的项目'
            }

        # 构建文献查询SQL
        sql = 'SELECT * FROM literature WHERE project_id = ?'
        params = [project_id]

        # 添加年份范围过滤
        if year_range and len(year_range) == 2:
            sql += ' AND year BETWEEN ? AND ?'
            params.extend(year_range)

        # 添加关键词过滤
        if keywords:
            keyword_conditions = []
            for keyword in keywords:
                keyword_conditions.append('(title LIKE ? OR abstract LIKE ? OR keywords LIKE ?)')
                params.extend([f'%{keyword}%', f'%{keyword}%', f'%{keyword}%'])
            sql += ' AND (' + ' OR '.join(keyword_conditions) + ')'

        # 限制结果数量
        sql += ' LIMIT ?'
        params.append(max_papers)

        # 执行查询
        papers = cursor.execute(sql, params).fetchall()
        conn.close()

        # 生成综述内容
        review_id = f'review_{uuid.uuid4().hex[:8]}'
        review_title = f'项目{project_id}的文献综述'
        review_content = f'# {review_title}\n\n'
        review_content += f'## 综述概述\n'
        review_content += f'本综述基于{len(papers)}篇相关文献，对项目{project_id}的研究主题进行了{review_type}分析。\n\n'

        # 添加文献列表
        if papers:
            review_content += '## 相关文献\n'
            for idx, paper in enumerate(papers, 1):
                review_content += f'{idx}. {paper[2]} - {paper[3]}\, {paper[5]}\n'
                review_content += f'   来源: {paper[4]}\, 年份: {paper[5]}\n\n'

        # 添加结论
        review_content += '## 研究结论\n'
        if not papers:
            review_content += '未找到相关文献。建议扩展关键词或年份范围。\n'
        else:
            review_content += f'基于{len(papers)}篇文献的分析，我们可以得出以下结论：\n'
            review_content += '1. 该领域的研究趋势是...\n'
            review_content += '2. 目前的研究空白包括...\n'
            review_content += '3. 未来的研究方向可以聚焦于...\n'

        return {
            'status': 'success',
            'message': '文献综述生成成功',
            'review_id': review_id,
            'review_title': review_title,
            'review_content': review_content,
            'paper_count': len(papers)
        }

    except Exception as e:
        return {
            'status': 'error',
            'message': f'生成文献综述时出错: {str(e)}'
        }